<template>
	<base-page class="base-form relation-select-dlg" :title="form.formName" @back="goBack">
		<view class="filter-box" v-if="filterWidgetList.length > 0">
			<online-filter-box @refresh="onRefresh" @reset="onReset">
				<view slot="sort"
					style="display: flex; flex-direction: row; align-items: center; justify-content: space-between;">
					<view style="display: flex;flex-direction: row;align-items: center;">
						<view v-for="sortItem in sortList" :key="sortItem.id" @click="onSortChange(sortItem)"
							class="sort-item"
							style="display: flex;flex-direction: row;align-items: center;justify-content: center;">
							<text class="sort-txt"
								:class="{sortActive:sortInfoActive === sortItem.fieldName}">{{sortItem.showName}}</text>
							<view :class="['mobile-font' , sortItem.asc ? 'icon-asc' : 'icon-desc']"
								style="color:#707070;font-size:28rpx;"></view>
						</view>
					</view>
				</view>
				<!-- 过滤字段 -->
				<online-custom-block subWidgetClass="filter-item" :widgetList="filterWidgetList" />
			</online-filter-box>
		</view>
		<view class="main-box">
			<!-- 列表 -->
			<view class="list" style="height: 500px;">
				<custom-list
					ref="cardList"
					height="100%"
					:isLoading="tableWidget.loading"
          :finished="tableWidget.finished"
          :dataList="tableWidget.dataList"
          @load="tableWidget.loadDataList"
				>
					<view class="list-item" v-for="(data ,index) in tableWidget.dataList" :key="index">
						<online-image-card :widget="cardWidget" :supportSelect="true" :rowData="data"
							:masterTable="masterTable" :isSelect="isSelect(data)"
							style="background: white; margin: 15px 0px;" :parentWidget="queryTable"
							@select="onSelectChange" />
					</view>
				</custom-list>
			</view>
		</view>
		<view class="menu-box">
			<u-button @click="goBack()" size="medium" :custom-style="customStyle">取消</u-button>
			<u-button :custom-style="{width: '100%'}" style="flex-grow: 1; margin-left: 8px" type="primary" size="medium" @click="onSubmit()">保存</u-button>
		</view>
	</base-page>
</template>

<script>
	import {
		OnlineFormMixins
	} from './onlineFormMixins.js';
	import { DropdownWidget, TableWidget } from '@/utils/widget.js';

	export default {
		name: 'relationQueryForm',
		props: {
			value: {
				type: [Number, String, Array]
			},
			rowKey: {
				type: String,
				default: 'deptId'
			},
			formConfig: {
				type: Object
			}
		},
		mixins: [OnlineFormMixins],
		provide() {
			return {
				form: () => {
					return {
						...this.form,
						getWidgetValue: this.getWidgetValue,
						onValueChange: this.onValueChange,
						getWidgetVisible: this.getWidgetVisible,
						onWidgetValueChange: this.onWidgetValueChange,
						getDictDataList: this.getDictDataList,
						getDropdownParams: this.getDropdownParams,
						getPrimaryData: this.getPrimaryData,
						masterTable: this.masterTable
					}
				}
			}
		},
		data() {
			return {
				selectItemList: [],
				isUpdateFrom: 0,
				sortInfo: undefined,
				sortInfoActive: null,
				pageSize: 20,
				customStyle: {
					borderRadius: '0',
					border: '1px solid #ebedf0'
				},
				customStyle1: {
					borderRadius: '0',
				},
				tableWidget: new TableWidget(this.loadTableData, this.loadTableDataVerify, true),
			}
		},
		methods: {
			goBack() {
				this.$emit('close', false, this.selectItemList);
			},
			onSubmit() {
				this.$emit('close', true, this.selectItemList);
			},
			onRefresh() {
				this.onCancelDelete();
				this.pageNum = 1;
				if (this.$refs.cardList) this.$refs.cardList.reset();
			},
			onReset() {
				if (Array.isArray(this.filterWidgetList)) {
					this.filterWidgetList.forEach(widget => {
						this.onValueChange(widget, undefined);
					});
					if (this.$refs.cardList) this.$refs.cardList.reset();
				}
			},
			isSelect(data) {
				if (data == null) return false;
				let find = false;
				let primaryKey = ((this.queryTable.table || {}).primaryKeyColumn || {}).columnName;
				if (primaryKey) {
					for (let i = 0; i < this.selectItemList.length; i++) {
						if (this.selectItemList[i][primaryKey] === data[primaryKey]) { // fix小程序里两个对象不全等
							find = true;
							break;
						}
					}
				}
				return find;
			},
			onSelectChange(data, val) {
				this.selectItemList = [data];
			},
			onSortChange(sortInfo) {
				if (sortInfo.asc == null) {
					sortInfo.asc = true;
				} else if (sortInfo.asc === true) {
					sortInfo.asc = false;
				} else if (sortInfo.asc === false) {
					// sortInfo.asc = undefined;
					sortInfo.asc = true;
				}
				if (sortInfo.asc != null) {
					this.sortInfoActive = sortInfo.fieldName
					this.sortInfo = {
						fieldName: sortInfo.fieldName,
						asc: sortInfo.asc
					}
				} else {
					this.sortInfo = undefined;
				}
				this.onRefresh();
			},
			loadTableDataVerify() {
				return true;
			},
			async loadTableData(params) {
				try {
					let table = this.queryTable.table;
					if (table == null) {
						throw new Error('未配置关联表');
					}
					if (params == null) params = {};

					params = {
						...params,
						orderParam: this.sortInfo == null ? [] : [this.sortInfo]
					}
					params.datasourceId = table.datasource.datasourceId;
					params.filterDtoList = this.getQueryParams(this.filterWidgetList);
					if (this.queryTable.relation != null) {
						params.relationId = table.relation.relationId;
					}
					if (typeof this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] ===
						'function') {
						params = await this.queryTable.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](params);
					}
					if (params == null) {
						throw new Error('取消加载数据');
					}
					let res = await this.doUrl(
						`/admin/online/onlineOperation/listByOneToManyRelationId/${table.datasource.variableName}`,
						'post',
						params
					);

					if (typeof this.queryTable.eventInfo[this.OnlineFormEventType
							.AFTER_LOAD_TABLE_DATA] === 'function') {
						res.dataList = await this.queryTable.eventInfo[this.OnlineFormEventType
							.AFTER_LOAD_TABLE_DATA](res.dataList);
					}
					return {
						dataList: res.dataList,
						totalCount: res.totalCount
					};
				} catch (e) {
					console.error(e);
					throw e;
				}
			},
			getListParent(sender) {
				return sender.$parent.$parent;
			}
		},
		computed: {
			form() {
				this.isUpdateFrom++
				return this.buildFormConfig(this.formConfig);
			},
			queryTable() {
				return this.formConfig.tableWidget;
			},
			cardWidget() {
				return this.queryTable.childWidgetList[0];
			},
			filterWidgetList() {
				return this.queryTable.childWidgetList.slice(1);
			},
			sortList() {
				return this.queryTable.props.orderList;
			}
		},
		watch: {
			isUpdateFrom: {
				handler() {
					this.isReady = false;
					this.initPage();
					this.initFormWidgetList();
					if (this.form.eventInfo && typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM] === 'function') {
						this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM]();
					}
					this.initWidgetLinkage(this.form.formType);
					this.isReady = true;
				},
				immediate: true
			}
		},
		mounted() {
			this.$nextTick(() => {
				if (this.$refs.cardList) {
					this.$refs.cardList.reset();
				}
			})

		}
	}
</script>

<style scoped lang="less">
	.relation-select-dlg {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #F6F7F9;

		.main-box {
			display: flex;
			flex-direction: column;
			height: 100%;
		}

		.menu-box {
			flex-grow: 0;
			flex-shrink: 0;
			width: 100%;
			padding: 20rpx 30rpx;
			flex-wrap: nowrap;
			background: white;
			box-sizing: border-box;
			margin-top: 30rpx;

			button::after {
				border-radius: 0;
				border: none;
			}

			&>u-button,
			&>.u-btn {
				&:first-child {
					width: 24%;
				}

				&:last-child {
					width: 74%;
				}
			}
		}

		.filter-box {
			background: white;
			padding: 0px 36rpx;
			flex-grow: 0;
			flex-shrink: 0;
		}

		.sort-item+.sort-item {
			margin-left: 16rpx;
		}

		.sort-txt {
			font-size: 28rpx;
			color: #707070;
			margin-right: 2rpx;
		}

		.list {
			flex-grow: 1;
			flex-shrink: 1;
			padding: 4rpx 32rpx 32rpx 32rpx;
			position: relative;
		}
	}
</style>